package com.weiwu.weiwustore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weiwu.weiwustore.entity.Apply_record;
import com.weiwu.weiwustore.entity.Role;
import com.weiwu.weiwustore.entity.Store;
import com.weiwu.weiwustore.entity.User;
import com.weiwu.weiwustore.mapper.Apply_recordMapper;
import com.weiwu.weiwustore.mapper.RoleMapper;
import com.weiwu.weiwustore.mapper.StoreMapper;

import com.weiwu.weiwustore.mapper.UserMapper;
import com.weiwu.weiwustore.pojo.SelectItem;
import com.weiwu.weiwustore.pojo.UserD;
import com.weiwu.weiwustore.pojo.UserP;
import com.weiwu.weiwustore.service.UserService;
import com.weiwu.weiwustore.utils.Md5;
import com.weiwu.weiwustore.utils.ObjectFormatUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

import static com.weiwu.weiwustore.utils.ObjectFormatUtil.toInteger;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    StoreMapper storeMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    Apply_recordMapper apply_recordMapper;

    @Override
    public Integer findCount() {
        return userMapper.selectCount(null);
    }

    @Override
    public User findUserByEmail(String principal) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("email", principal));
    }

    @Override
    public UserD findUserDByEmail(String principal) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("email", principal));
        String StoreStr = "暂无";
        Store store;
        // 格式化显示所负责的仓库
        if (user.getStoreid() != null) {
            store = storeMapper.selectById(user.getStoreid());
            StoreStr = store.getSname();
        }
        // 格式化时间
        String EntryDate = String.format("%tF", user.getEntryDate());
        // 格式化显示角色
        Role role = roleMapper.selectById(user.getRoleid());
        return new UserD(user.getUname(), role.getRole(), user.getSex(), StoreStr, EntryDate, user.getEmail(), user.getPhone(), "", user.getId());
    }

    @Override
    public List<UserP> findUserPsByCondition(Map<String, Object> map) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        Integer size = 10, page = 1;
        IPage pageP = new Page(page, size);
        if (map.containsKey("storeid")) {
            if (map.get("storeid") != "") {
                wrapper.eq("storeid", map.get("storeid"));
            }
        }
        if (map.containsKey("uname")) {
            if (map.get("uname") != "") {
                wrapper.like("uname", map.get("uname"));
            }
        }
        if (map.containsKey("size")) {
            size = toInteger(map.get("size"));
        }
        if (map.containsKey("page")) {
            page = ObjectFormatUtil.toInteger(map.get("page"));
        }
        pageP.setSize(size);
        pageP.setCurrent(page);
        IPage list = userMapper.selectPage(pageP, wrapper);
        return pack(list.getRecords());
    }

    // 新增 注册&用户管理新增
    @Override
    public Integer insertUser(Map<String, Object> map) {
        // 检查邮箱是否重复
        String email = String.valueOf(map.get("email"));
        if (userMapper.selectOne(new QueryWrapper<User>().eq("email", email)) != null) {
            return -1;
        }
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date entry = new Date();
        try {
            entry = format.parse(String.valueOf(map.get("entryDate")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        User user = new User(String.valueOf(map.get("uname")), String.valueOf(map.get("sex")),
                entry, String.valueOf(map.get("phone")), email,
                String.valueOf(map.get("pwd")));
        return userMapper.insert(user);
    }

    @Override
    public Integer updateUser(Map<String, Object> map) {
        // 修改
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date entryDate = new Date();
        try {
            entryDate = format.parse(String.valueOf(map.get("entryDate")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        QueryWrapper<Store> wrapper01 = new QueryWrapper<>();
        Integer roleid = 0, storeid = 0;
        if (String.valueOf(map.get("authority")).contains("员") || String.valueOf(map.get("authority")).contains("仓")) {
            wrapper.eq("role", String.valueOf(map.get("authority")));
            Role role = roleMapper.selectOne(wrapper);
            roleid = role.getId();
        } else {
            roleid = toInteger(map.get("authority"));
        }
        if (String.valueOf(map.get("storeid")).contains("仓")) {
            wrapper01.eq("sname", String.valueOf(map.get("storeid")));
            storeid = storeMapper.selectOne(wrapper01).getId();
        } else {
            storeid = toInteger(map.get("storeid"));
        }
        User user = new User(toInteger(map.get("id")), String.valueOf(map.get("uname")),
                roleid, storeid, String.valueOf(map.get("sex")),
                entryDate,
                String.valueOf(map.get("phone")));
        return userMapper.updateById(user);
    }

    @Override
    public Integer accountupdate(Map<String, Object> map) {
        if (map.size() != 5) {
            return -1;
        }
        User user = new User(String.valueOf(map.get("userName")), String.valueOf(map.get("phone")),
                String.valueOf(map.get("sex")), String.valueOf(map.get("pwd")), toInteger(map.get("id")));
        return userMapper.updateById(user);
    }

    @Override
    public Integer updateUserPwd(Map<String, Object> map) {
        return userMapper.update(new User(Md5.crypt(String.valueOf(map.get("email")))),
                new QueryWrapper<User>().eq("id", String.valueOf(map.get("id"))));
    }

    @Override
    public Integer deleteUserById(Integer id) {
        // 如果此用户还有申请单，则不能删除
        QueryWrapper<Apply_record> wrapper = new QueryWrapper<>();
        wrapper.and(i -> i.eq("reviewerid", id).or().eq("checkerid", id).or().eq("applicantid", id));
        List<Apply_record> lists = apply_recordMapper.selectList(wrapper);
        if (lists != null || lists.size() != 0) {
            return -1;
        }
        return userMapper.deleteById(id);
    }


    private List<UserP> pack(List<User> list) {
        List<UserP> result = new ArrayList<>();
        for (User u : list) {
            result.add(singlePack(u));
        }
        return result;
    }

    @Override
    public UserP singlePack(User user) {
        UserP userP = new UserP(user);
        if (user.getStoreid() == null) {
            userP.setStoreName("暂无");
        } else {
            userP.setStoreName(storeMapper.selectById(user.getStoreid()).getSname());
        }
        if (user.getRoleid() == null) {
            userP.setRole("暂无");
        } else {
            userP.setRole(roleMapper.selectById(user.getRoleid()).getRole());
        }
        return userP;
    }

    @Override
    public List<SelectItem> getmaterialitembystoreid(Map<String, Object> map) {
        String storeid = String.valueOf(map.get("storeid"));
        List<User> userLsit = userMapper.selectList(new QueryWrapper<User>().eq("storeid", storeid).eq("roleid", 1));
        List<SelectItem> res = new ArrayList<>();
        for (User u : userLsit) {
            res.add(new SelectItem(u.getId().toString(), u.getUname()));
        }
        return res;
    }
}
